package elitech.vietnam.myfashion;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;

import elitech.vietnam.autoupdate.ZipUtility;
import elitech.vietnam.myfashion.dialog.MyDialogHandler;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Member;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.wsclient.Utilities;

public class SplashScreen extends Activity {

	public static boolean loadingCompleted = false;

//	private ImageView splash_imageview;
	private ProgressBar splash_progressbar;
	private Animation anim;
	private TextView txtStatus;
	
	boolean loaded = false;

	// /////////////////////////////Hung-Auto update////////////////////////////
	private final int BEGIN_DOWNLOAD_UPDATE = 1;
	private final int DOWNLOAD_UPDATE = 2;
	private final int END_DOWNLOAD_UPDATE = 3;
	private final int SHOW_DOWNLOAD_UPDATE = 4;
	private final int START_APP = 5;
	private int VersionCode;
	private String VersionName = "";
	private Integer size;
	private String ApkName;
	private String AppName;
	private String BuildVersionPath = "";
	private String urlpath;
	private String PackageName;
	private boolean flagupdateversion = false;
	private AlertDialog.Builder builder;
	private ProgressDialog progressBar;
	private Boolean isInstalled = false;
	private SharedPreferences mPrefs;
	
	class PInfo {
		private String appname = "";
		private String versionName = "";
		private int versionCode = 0;
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case START_APP:
				startApp();
				break;
			case BEGIN_DOWNLOAD_UPDATE:
				progressBar.show();
				break;
			case DOWNLOAD_UPDATE:
				Integer i = (Integer) msg.obj;
				Log.i("================", "" + i);
				progressBar.setProgress(i);
				break;
			case END_DOWNLOAD_UPDATE:
				progressBar.dismiss();
				break;
			case SHOW_DOWNLOAD_UPDATE:
				String str = getResources().getString(R.string.your_version)
						+ " "
						+ getInstallPackageVersionInfo(AppName.toString())
								.toString()
						+ getResources().getString(R.string.you_want_install)
						+ " " + VersionName.toString() + "?";
				builder.setTitle(R.string.app_name);
				builder.setMessage(str);
				builder.setCancelable(false);
				builder.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								threadDownload.start();
							}

						});
				builder.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								// startActivity(myIntent);
								// finish();
								startApp();
							}

						});
				builder.show();
				break;
			default:
				break;
			}
		}
	}; // handler

	Thread thread = new Thread(new Runnable() {
		public void run() {
			try {
				// Thread.sleep(1000);
				if (flagupdateversion == false) {
					ApkName = "MyFashion.zip";
					AppName = getResources().getString(R.string.app_name);
					BuildVersionPath = "http://eli6.cafe24.com/AutoUpdateAndroid/Shopping/auto_update.txt"
							.toString();
//					BuildVersionPath = "http://elisoft.co.kr/AutoUpdateAndroid/Shopping/auto_update.txt"
//							.toString();
					PackageName = "elitech.vietnam.myfashion".toString();
					// option.setMyVersion(MyVersionName);
					// app.setOption(option);
					try {
						GetVersionFromServer(BuildVersionPath);
						checkInstalledApp(AppName.toString());
						// if (checkInstalledApp(AppName.toString()) == false) {
						// startActivity(myIntent);
						// finish();
						// }
					} catch (Exception er) {
						// Toast.makeText(getApplicationContext(),
						// er.getMessage(), Toast.LENGTH_SHORT).show();
						Log.e("Auto update", er.getMessage());
						// startActivity(myIntent);
						// finish();
						// startApp();
						handler.sendEmptyMessage(START_APP);
					}
					flagupdateversion = true;
				}

			} catch (Exception e) {
				// fLog.Write("Check autoupdate: Exception threadDownload"+e.getMessage());
				// Toast.makeText(getApplicationContext(), e.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}
		}
	});

	/**
	 * Get version form file in server
	 * 
	 * @param BuildVersionPath
	 *            Path file
	 */
	public String GetVersionFromServer(String BuildVersionPath)
			throws Exception {
		URL u;
		// try {
		u = new URL(BuildVersionPath.toString());

		HttpURLConnection c = (HttpURLConnection) u.openConnection();
		c.setRequestMethod("GET");
		c.setDoOutput(true);
		c.connect();
		InputStream in = c.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		byte[] buffer = new byte[1024];
		int len1 = 0;
		while ((len1 = in.read(buffer)) != -1) {
			baos.write(buffer, 0, len1); // Write Into ByteArrayOutputStream
											// Buffer.
		}
		String temp = "";
		String s = baos.toString();
		int iPost = s.indexOf("=");
		if (iPost == -1)
			return VersionName;
		temp = s.substring(iPost + 2, s.indexOf(";"));
		iPost = s.lastIndexOf("=");
		temp += s.substring(iPost + 1, s.lastIndexOf(";"));
		temp.trim();
		String[] fields = temp.split(" ");
		VersionCode = Integer.parseInt(fields[0].toString());//
		VersionName = fields[1].toString();
		baos.close();
		c.disconnect();
		return VersionName;
	}

	/**
	 * Check app install on device
	 * 
	 * @param appName
	 *            App name
	 */
	private void checkInstalledApp(String appName) throws Exception {
		getPackages(appName);
	}

	/**
	 * Get packet info app install on device
	 * 
	 * @param appName
	 *            App name
	 */
	private void getPackages(String appName) throws Exception {

		ArrayList<PInfo> apps = getInstalledApps(false); /*
														 * false = no system
														 * packages
														 */
		isInstalled = false;
		int max = apps.size();

		for (int i = 0; i < max; i++) {
			if (apps.get(i).appname.toString().equals(appName.toString())) {
				// System.out.println("b2");
				/*
				 * if(apps.get(i).versionName.toString().contains(VersionName.
				 * toString()) == true && VersionCode ==
				 * apps.get(i).versionCode) { isInstalled = true;
				 * Toast.makeText(getApplicationContext(), "Code Match",
				 * Toast.LENGTH_SHORT).show(); openMyDialog(); }
				 */
				// MyVersionName =
				// getInstallPackageVersionInfo(AppName.toString())
				// .toString();
				if (VersionCode <= apps.get(i).versionCode) {
					isInstalled = false;
				} else if (VersionCode > apps.get(i).versionCode) {
					isInstalled = true;
					Message mes = handler.obtainMessage(SHOW_DOWNLOAD_UPDATE);
					handler.sendMessage(mes);
					mes = null;
				}
				break;
			}
		}
		if (isInstalled == false) {
			// startActivity(myIntent);
			// finish();
			handler.sendEmptyMessage(START_APP);
		}
		// else
		// {
		// startApp();
		// }
	}

	private void startApp() {

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {

				loadingCompleted();
			}
		}, 1000);
	}

	Thread threadDownload = new Thread(new Runnable() {
		public void run() {
			try {
				Message mes = handler.obtainMessage(BEGIN_DOWNLOAD_UPDATE);
				handler.sendMessage(mes);
				mes = null;
				// fLog.Write("Check autoupdate: DownloadOnSDcard");
				DownloadOnSDcard();
				mes = handler.obtainMessage(END_DOWNLOAD_UPDATE);
				handler.sendMessage(mes);
				mes = null;
				// fLog.Write("Check autoupdate: InstallApplication");
				InstallApplication();
				// fLog.Write("Check autoupdate: UnInstallApplication");
				// UnInstallApplication(PackageName.toString());
				finish();
			} catch (Exception e) {
				// Toast.makeText(getApplicationContext(), e.getMessage(),
				// Toast.LENGTH_SHORT).show();
				Log.e("Thread auto update error", "" + e.getMessage());
				// startActivity(myIntent);
				// finish();
				// startApp();
				handler.sendEmptyMessage(START_APP);
			}
		}
	});

	/**
	 * Get version code of app
	 * 
	 * @param getSysPackages
	 *            true ystem packages - false no system packages
	 */
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
		ArrayList<PInfo> res = new ArrayList<PInfo>();
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue;
			}
			if (p.applicationInfo.loadLabel(getPackageManager()).toString()
					.equals(AppName)) {
				PInfo newInfo = new PInfo();
				newInfo.appname = p.applicationInfo.loadLabel(
						getPackageManager()).toString();
				// newInfo.pname = p.packageName;
				newInfo.versionName = p.versionName;
				newInfo.versionCode = p.versionCode;
				// newInfo.icon =
				// p.applicationInfo.loadIcon(getPackageManager());
				// /System.out.println(p.applicationInfo.loadLabel(getPackageManager()).toString()+"-"+p.packageName+"-"+p.versionName
				// +" - "+ p.versionCode);
				res.add(newInfo);
				return res;
			}
		}
		return res;
	}

	/**
	 * Download file form server to sdcard
	 * 
	 */
	public void DownloadOnSDcard() throws Exception {
		ApkName = "MyFashion.zip";
		urlpath = "http://eli6.cafe24.com/AutoUpdateAndroid/Shopping/" + "Shopping_Project"
				+ VersionCode + ".zip";
//		urlpath = "http://elisoft.co.kr/AutoUpdateAndroid/Shopping/" + "Shopping_Project"
//				+ VersionCode + ".zip";
		URL url = new URL(urlpath.toString()); // Your given URL.

		HttpURLConnection c = (HttpURLConnection) url.openConnection();
		c.setRequestMethod("GET");
		c.setDoOutput(true);
		c.connect(); // Connection Complete here.!
		// Toast.makeText(getApplicationContext(),
		// "HttpURLConnection complete.", Toast.LENGTH_SHORT).show();
		size = c.getContentLength();
		Integer total = 0;
		String PATH = Environment.getExternalStorageDirectory()
				+ "/download/Shopping Project/";
		File file = new File(PATH); // PATH = /mnt/sdcard/download/
		if (!file.exists()) {
			file.mkdirs();
		}
		File outputFile = new File(file, ApkName.toString());
		FileOutputStream fos = new FileOutputStream(outputFile);
		InputStream is = c.getInputStream(); // Get from Server and Catch In
												// Input Stream Object.
		byte[] buffer = new byte[1024];
		int len1 = 0;

		Message mes;// = handler

		while ((len1 = is.read(buffer)) != -1) {
			total += len1;
			mes = handler.obtainMessage(DOWNLOAD_UPDATE, (total * 100) / size);
			handler.sendMessage(mes);
			mes = null;
			fos.write(buffer, 0, len1); // Write In FileOutputStream.
		}
		fos.close();
		is.close();
		c.disconnect();
		// Unzip
		ZipUtility.unzip(outputFile, file);
		outputFile.delete();
	}

	public void InstallApplication() {
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
				packageURI);
		intent.setDataAndType(
				Uri.fromFile(new File(Environment.getExternalStorageDirectory()
						+ "/download/Shopping Project/MyFashion.apk")),
				"application/vnd.android.package-archive");
		startActivity(intent);

	}

	public void UnInstallApplication(String packageName)// Specific package Name
														// Uninstall.
	{
		// Uri packageURI = Uri.parse("package:com.CheckInstallApp");
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent);
	}

	public String getInstallPackageVersionInfo(String appName) {
		String InstallVersion = "";
		ArrayList<PInfo> apps = getInstalledApps(false); /*
														 * false = no system
														 * packages
														 */
		final int max = apps.size();
		for (int i = 0; i < max; i++) {
			// apps.get(i).prettyPrint();

			if (apps.get(i).appname.toString().equals(appName.toString())) {
				// InstallVersion = "Install Version Code: "+
				// apps.get(i).versionCode+
				// " Version Name: "+ apps.get(i).versionName.toString();
				InstallVersion = apps.get(i).versionName.toString();
				break;
			}
		}
		return InstallVersion.toString();
	}

	// /////////////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash_screen);
		splash_progressbar = (ProgressBar) findViewById(R.id.splash_progressbar);
		txtStatus = (TextView) findViewById(R.id.splash_txtStatus);
		mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		loadingCompleted = false;
		try {
			if (!Utilities.isNetworkEnabled(getApplicationContext())) {
				new AlertDialog.Builder(this)
						.setTitle(getString(R.string.no_internet_connection))
						.setMessage(
								getString(R.string.internet_connection_request))
						.setPositiveButton(getString(R.string.ok),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Intent intent = new Intent(
												Settings.ACTION_WIFI_SETTINGS);
										startActivity(intent);
									}
								})
						.setNegativeButton(getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										finish();
									}
								}).create().show();
				return;
			}

			StartAnimation();
			// ////Hung-Autoupdate////////////////////////////////////////////////////
			size = 0;
			builder = new AlertDialog.Builder(this);
			String s = getResources().getString(R.string.loading) + "...";
			progressBar = new ProgressDialog(this);
			progressBar.setCancelable(false);
			progressBar.setMessage(s);
			progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			thread.start();
			startApp();

			// ///////////////////////////////////////////////////////////////////////

		} catch (Exception e) {
			//
			Log.e("Thread auto update error", "" + e.getMessage());
			startApp();
		}
	}

	public void EnableLoadingBar(boolean state) {
		if (state) {
//			splash_imageview.setVisibility(View.INVISIBLE);
			splash_progressbar.setVisibility(View.VISIBLE);
		} else {
//			splash_imageview.setVisibility(View.VISIBLE);
			splash_progressbar.setVisibility(View.INVISIBLE);
		}
	}

	private void StartAnimation() {
		anim = AnimationUtils.loadAnimation(SplashScreen.this,
				R.anim.fade_splash);
		anim.reset();
//		splash_imageview.clearAnimation();
//		splash_imageview.startAnimation(anim);
	}

	public synchronized void onLoadCompleted() {
		if (loaded)
			return;
		Log.w("SplashScreen", "Start MainActivity");
		loaded = true;
		GetLastData();
		Intent intent = new Intent(SplashScreen.this, MainActivity.class);
		startActivity(intent);
		SplashScreen.this.finish();
	}
	
	public Member mUser;
	
	void GetLastData() {
		Gson gson = new Gson();

		String user = GetPreference("User");
		if (!user.equals("")) {
			mUser = gson.fromJson(user, Member.class);
		}
		
		String best = GetPreference("ListProductBest");
		if (best.equals("")) {
			new CallServiceTask() {
				private ArrayList<Product> rs = new ArrayList<Product>();

				protected void onPreExecute() {
					txtStatus.setText(R.string.firsttime);
				};
				
				public void work() {
					try {
						if(mUser==null)
							rs = service.getBestOfDay(new Date(), -1);
						else
							rs = service.getBestOfDay(new Date(), mUser.Id);
					} catch (IOException e) {
					} catch (XmlPullParserException e) {
					}
				};

				protected void onPostExecute(Void result) {
					if (rs == null)
						return;
					if (rs.size() == 0) {
						
					} else {
						AddPreference("ListProductBest", ConvertToJson(rs));
					}
				};
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
		
	}
	
	public String GetPreference(String tag) {
		return mPrefs.getString(tag, "");
	}
	
	public String ConvertToJson(Object O) {
		Gson gson = new Gson();
		return gson.toJson(O);
	}
	
	public void AddPreference(String tag, String value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putString(tag, value);
		editor.commit();
	}
	
	public synchronized void loadingCompleted() {
		if (!loadingCompleted) {
			loadingCompleted = true;
			//EnableLoadingBar(true);
		} else
			onLoadCompleted();
	}

	@Override
	public void onBackPressed() {
		new MyDialogHandler().confirm(this, getString(R.string.confirm_exit),
				getString(R.string.do_you_want_to_exit_),
				getString(R.string.cancel), getString(R.string.ok),
				new Runnable() {
					@Override
					public void run() {
						finish();
					}
				}, null);
	}
}
